"use client";

import { useEffect, useMemo, useState } from "react";
import type { AgentSummary } from "@agent-society/types";
import clsx from "clsx";
import type { Command, PaletteState } from "../lib/command-palette";
import { chargeCredits, createGovernanceTask, issueCredits } from "../lib/actions";

interface Props extends PaletteState {
  agents: AgentSummary[];
  roles: string[];
}

export function CommandConsole({ open, setOpen, commands, register, deregister, agents, roles }: Props) {
  const [query, setQuery] = useState("");

  useEffect(() => {
    const canOperate = roles.includes("operator") || roles.includes("admin");
    const canGovern = roles.includes("governance") || roles.includes("admin");
    const baseCommands: Command[] = [
      {
        id: "refresh-dashboard",
        label: "Refresh data",
        action: () => window.location.reload(),
        group: "General"
      },
      ...agents.map(agent => ({
        id: `focus-${agent.id}`,
        label: `Focus agent: ${agent.name}`,
        action: () => {
          const anchor = document.querySelector(`#agent-${agent.id}`) as HTMLElement | null;
          anchor?.scrollIntoView({ behavior: "smooth", block: "center" });
        },
        group: "Agents"
      }))
    ];
    const ledgerCommands: Command[] = !canOperate
      ? []
      : [
          ...agents.map(agent => ({
            id: `issue-${agent.id}`,
            label: `Issue 5 credits to ${agent.name}`,
            action: async () => issueCredits(agent.id, 5).catch(() => alert("Failed to issue credits (requires API)")),
            group: "Ledger"
          })),
          ...agents.map(agent => ({
            id: `charge-${agent.id}`,
            label: `Charge 3 credits from ${agent.name}`,
            action: async () => chargeCredits(agent.id, 3).catch(() => alert("Failed to charge credits (requires API)")),
            group: "Ledger"
          }))
        ];
    const governanceCommands: Command[] = !canGovern
      ? []
      : [
          {
            id: "gov-create",
            label: "Create governance task placeholder",
            action: async () =>
              createGovernanceTask("atlas", "zeus", "Console created task").catch(() =>
                alert("Failed to create task (requires API)")
              ),
            group: "Governance"
          }
        ];
    const agentCommands = [...baseCommands, ...ledgerCommands, ...governanceCommands];
    register(agentCommands);
    return () => {
      deregister(agentCommands.map(cmd => cmd.id));
    };
  }, [agents, register, deregister]);

  useEffect(() => {
    if (!open) setQuery("");
  }, [open]);

  useEffect(() => {
    function handle(event: KeyboardEvent) {
      if (event.key === "Escape") {
        setOpen(false);
      }
    }
    window.addEventListener("keydown", handle);
    return () => window.removeEventListener("keydown", handle);
  }, [setOpen]);

  const filtered = useMemo(() => {
    if (!query) return commands;
    const lowercase = query.toLowerCase();
    return commands.filter(cmd => cmd.label.toLowerCase().includes(lowercase));
  }, [commands, query]);

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-start justify-center bg-slate-950/80 backdrop-blur-sm">
      <div className="mt-24 w-full max-w-2xl rounded-2xl border border-slate-700/50 bg-slate-900/90 p-4 shadow-2xl">
        <input
          autoFocus
          value={query}
          onChange={event => setQuery(event.target.value)}
          placeholder="Type a command or search…"
          className="w-full rounded-lg border border-slate-700/50 bg-slate-900/80 px-3 py-2 text-sm text-slate-100 outline-none focus:border-sky-500"
        />
        <ul className="mt-3 max-h-80 overflow-y-auto">
          {filtered.map(cmd => (
            <li key={cmd.id}>
              <button
                type="button"
                onClick={() => {
                  cmd.action();
                  setOpen(false);
                }}
                className={clsx(
                  "flex w-full items-center justify-between rounded-lg border border-transparent px-3 py-2 text-left text-sm text-slate-200",
                  "hover:border-sky-500/40 hover:bg-sky-500/10"
                )}
              >
                <span>{cmd.label}</span>
                {cmd.group && <span className="text-xs uppercase tracking-wide text-slate-500">{cmd.group}</span>}
              </button>
            </li>
          ))}
          {filtered.length === 0 && (
            <li className="rounded-lg border border-dashed border-slate-700/50 px-3 py-6 text-center text-sm text-slate-500">
              No commands found.
            </li>
          )}
        </ul>
        <footer className="mt-3 flex items-center justify-between text-xs text-slate-500">
          <span>Press Esc to close</span>
          <button
            type="button"
            onClick={() => setOpen(false)}
            className="rounded border border-slate-700/50 px-2 py-1 hover:border-slate-500"
          >
            Close
          </button>
        </footer>
      </div>
    </div>
  );
}
